package com.app.samba.util;

import android.content.Context;
import android.os.Environment;
import android.os.storage.StorageManager;

import com.app.samba.DebugLog;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 创建文件
 * <p>
 * Created by jiangdongguo on 2017/10/18.
 */

public class FileUtils {

    private static BufferedOutputStream outputStream;
    public static String ROOT_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
    public static String HEAD_PATH = File.separator + "samba下载图片";
    public static String HEAD_FACE_PATH = File.separator + "人脸框";
    public static String HEAD_SCREEN_PATH = File.separator + "投屏框";

    public static void createfile(String path) {
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        try {
            outputStream = new BufferedOutputStream(new FileOutputStream(file));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void releaseFile() {
        try {
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void putFileStream(byte[] data, int offset, int length) {
        if (outputStream != null) {
            try {
                outputStream.write(data, offset, length);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void putFileStream(byte[] data) {
        if (outputStream != null) {
            try {
                outputStream.write(data);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建文件夹
     *
     * @param fileDirName 根目录
     */
    public static void createFileDir(String fileDirName) {
        File fileDir = new File(fileDirName);
        boolean isRootSuccess = false;
        if (!fileDir.exists()) {
            isRootSuccess = fileDir.mkdirs();
            DebugLog.d("isRootSuccess:" + isRootSuccess);
        }
    }

    /**
     * 获取外置存储路径
     *
     * @param mContext
     * @param is_removale
     * @return
     */
    public String getExtSDCardPath(Context mContext, boolean is_removale) {
        StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
        Class<?> storageVolumeClazz = null;
        try {
            storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
            Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
            Method getPath = storageVolumeClazz.getMethod("getPath");
            Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
            Object result = getVolumeList.invoke(mStorageManager);
            final int length = Array.getLength(result);
            for (int i = 0; i < length; i++) {
                Object storageVolumeElement = Array.get(result, i);
                String path = (String) getPath.invoke(storageVolumeElement);
                boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
                if (is_removale == removable) {
                    return path;
                }
            }

        } catch (ClassNotFoundException | InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 百度AI工具类
     */
    private static SimpleDateFormat sdf = new SimpleDateFormat("HHmmssSSS", Locale.CHINA);

    /**
     * 读取文件内容，作为字符串返回
     */
    public static String readFileAsString(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        }

        if (file.length() > 1024 * 1024 * 1024) {
            throw new IOException("File is too large");
        }

        StringBuilder sb = new StringBuilder((int) (file.length()));
        // 创建字节输入流
        FileInputStream fis = new FileInputStream(filePath);
        // 创建一个长度为10240的Buffer
        byte[] bbuf = new byte[10240];
        // 用于保存实际读取的字节数
        int hasRead = 0;
        while ((hasRead = fis.read(bbuf)) > 0) {
            sb.append(new String(bbuf, 0, hasRead));
        }
        fis.close();
        return sb.toString();
    }

    /**
     * 根据文件路径读取byte[] 数组,生成64
     */
    public static byte[] readFileByBytes(String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException(filePath);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
            BufferedInputStream in = null;

            try {
                in = new BufferedInputStream(new FileInputStream(file));
                short bufSize = 1024;
                byte[] buffer = new byte[bufSize];
                int len1;
                while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
                    bos.write(buffer, 0, len1);
                }

                byte[] var7 = bos.toByteArray();
                return var7;
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException var14) {
                    var14.printStackTrace();
                }

                bos.close();
            }
        }
    }

    /**
     * 保存人头路径
     *
     * @param bitmapByte 人脸流
     */
    public static String saveHeadPic(byte[] bitmapByte, String headDir) {
//    headDir=    FileUtils.ROOT_PATH+AppUtil.getPackageName(MyApplication.getContext())++ FileUtils.HEAD_PATH
        String filePath = headDir + File.separator + sdf.format(new Date()) + ".png";
        DebugLog.d(DebugLog.LOG + " saveHeadPic--- filePath " + filePath);
        File filePng = new File(filePath);
        try {
            getFilesRead(filePng, bitmapByte);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filePath;
    }

    /**
     * 读流进去
     *
     * @param file 文件
     * @param mData
     * @throws IOException
     */
    public static void getFilesRead(File file, byte[] mData) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(mData, 0, mData.length));
        FileOutputStream fos = new FileOutputStream(file);
        byte[] buff = new byte[8192];
        int len;
        while ((len = bis.read(buff)) != -1) {
            fos.write(buff, 0, len);
        }
        fos.flush();
        fos.close();
        bis.close();


    }
    /**
     * 保存人头路径
     *
     * @param bitmapByte 人脸流
     */
    public static String saveScreenPic(byte[] bitmapByte, String headDir) {
//    headDir=    FileUtils.ROOT_PATH+AppUtil.getPackageName(MyApplication.getContext())++ FileUtils.HEAD_PATH
        String filePath = headDir + File.separator + sdf.format(new Date()) + ".png";
        DebugLog.d(DebugLog.LOG + " saveHeadPic--- filePath " + filePath);
        File filePng = new File(filePath);
        try {
            readToPath(filePng, bitmapByte);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filePath;
    }
    /**
     * 读流进去
     *
     * @param file 文件
     * @param mData
     * @throws IOException
     */
    public static void readToPath(File file, byte[] mData) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(mData, 0, mData.length));
        FileOutputStream fos = new FileOutputStream(file);
        byte[] buff = new byte[8192];
        int len;
        while ((len = bis.read(buff)) != -1) {
            fos.write(buff, 0, len);
        }
        fos.flush();
        fos.close();
        bis.close();
//        DebugLog.d(LOGHsc+" beans----截屏完毕----   ");
//        EventBus.getDefault().post(new MessageEvent(SCREEN_FINISH,new ArrayList<>()));
    }


    /**
     * 生成md5
     * @param file 图片文件
     * @return MD5值
     * @throws FileNotFoundException
     */
    public static String getStringMd5(File file) throws FileNotFoundException {
        String value = null;
        FileInputStream in = new FileInputStream(file);
        try {
            MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(byteBuffer);
            BigInteger bi = new BigInteger(1, md5.digest());
            value = bi.toString(16);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return value;
    }

    /**
     * 根据图片路径删除没有人脸的图片
     * @param path 路径
     */
    public static void deletePicByPath(String path){
            File file = new File(path);
        if(file.exists()){
            boolean delete = file.delete();//执行删除
//            DebugLog.d(DebugLog.LOGHsc+" 删除无人脸的图片 "+(delete?"成功":"失败"));
        }
    }

    /**
     * 判断文件是否存在
     * @param path
     * @return
     */
   public static boolean isFileExist(String path){
       File file = new File(path);
       return file.exists();
   }


}
